$(document).ready(function(){
	init();
	window.check = $('.checkbox');
	window.errorMark = $('.errorMark');
});

function init(){
	$('.itemRow').mouseover(function(){
		$('#descriptionColumn').html($(this).attr('title'));
	});
	tabID = "#storeOuter";
	setUpJQueryUIElements(tabID);	
	keyListener();
	validate();
}

function showDescription(){
	$('#descriptionColumn').html($(this).attr('title'));
}

function setUpJQueryUIElements(tabID)
{
	$(tabID).tabs();
	$(':button').button();	
}

function validate()
{
	totalCost = 0;
	totalWeight = 0;
	costOK = false;
	weightOK = false;
	charRegEx=/[^0-9\.]/g;
	$(':text').each(function(index){
		if ($(this).val().match(charRegEx)) {
			alert('Input must be characters only');
			$(this).val($(this).val().replace(charRegEx,''));
		}
		thisCost=$(this).val() * $(this).parent().prevAll('.cost').last().html();
		thisWeight=$(this).val() * $(this).parent().prevAll('.weight').last().html();
		totalCost+=thisCost;
		totalWeight+=thisWeight;
		$(this).parent().nextAll('.costTotal').first().html(thisCost);
		$(this).parent().nextAll('.weightTotal').first().html(thisWeight);
	});
	$('#sumCost').html(totalCost);
	$('#sumWeight').html(totalWeight);
	if (totalCost > $('#shopperFunds').html()) {
		$('.costTotal').addClass('redText');
	} else {
		$('.costTotal').removeClass('redText');
		costOK=true;
	}
	if (totalWeight > $('#shopperWeightLimit').html()) {
		$('.weightTotal').addClass('redText');
	} else {
		$('.weightTotal').removeClass('redText');
		weightOK=true;
	}
	return weightOK&costOK;
}

function submitPurchases() {
	if (validate()) {
		cleanData();
		return true;
	} else {
		return false;
	}

}

function cleanData(){
	$(':text').each(function(index){
		if ($(this).val()==''){
			$(this).val(0);
		}
	});
}

function keyListener()
{
	$(':text').keypress(function(event) {
		$this = jQuery(event.target);
		validate();
	});
	
	$(':text').keyup(function(event) {
		$this = jQuery(event.target);
		validate();
	}); 
}